package com.eden.api.security.service;

import com.eden.api.security.LoginUser;
import com.eden.common.constant.Constants;
import com.eden.common.utils.CacheUtils;
import com.eden.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * @description: ehcache token
 * @author: wenqing
 * @date: 2020/3/19 14:31
 * @version: 1.0
 */

@ConditionalOnProperty(prefix="spring.cache", name="type", havingValue ="ehcache")
@Configuration
public class EhcacheTokenService extends AbstractTokenService {

    public static final String LOGIN_USER_TOKEN_CACHE = "login_tokens";
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    // 令牌自定义标识
    @Value("${api.token.header}")
    private String header;

    // 令牌秘钥
    @Value("${api.token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${api.token.expireTime}")
    private int expireTime;

    @PostConstruct
    public void init() {
        super.secret = secret;
        super.header = header;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    @Override
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            Object cacheObj = CacheUtils.get(LOGIN_USER_TOKEN_CACHE, userKey);
            if (StringUtils.isNotNull(cacheObj))
            {
                LoginUser user = StringUtils.cast(cacheObj);
                return user;
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    @Override
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
//            String userKey = getTokenKey(loginUser.getToken());
//            CacheUtils.put(LOGIN_USER_TOKEN_CACHE, userKey, loginUser);
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    @Override
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            CacheUtils.remove(LOGIN_USER_TOKEN_CACHE, userKey);
        }
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser 登录用户
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        CacheUtils.put(LOGIN_USER_TOKEN_CACHE, userKey, loginUser);
    }
}
